# -*- encoding: utf-8 -*-

"""
------------------------------------------
@File       : coroutine_base.py
@Author     : maixiaochai
@Email      : maixiaochai@outlook.com
@CreatedOn  : 2021/6/17 15:50
------------------------------------------
"""
from time import sleep


def minimize():
    """
        每次返回自传入数据开始到本次传入数据为止的最小值
    """
    print("minimize start")
    current = yield  # F
    print("first current: ", current)   # G

    while True:
        print("while start")  # A
        value = yield current  # B
        print("value | current: ", f"{value} | {current}")  # C
        current = min(value, current)  # D
        print("current: ", current)  # E


def demo():
    """     说明：
                每次 send之后，send给生成器的值并不是赋给 yield后边的内容，
                而是赋给了等号左边的变量。
                然后，执行到下个 yield表达式之间的代码，在下一个 yield current时，
                这个 current 经过了（如果是在while下）两个0.5 个while循环组成的代码。

                或者说，在while下，每个yield 的生命周期内的执行步骤为：
                    B(value = yield部分) -> C -> D -> E -> A -> B( current部分，将current返回)

                d.send(1)的 yield 周期内的执行步骤为：
                    F -> G -> A -> B(current部分，将current返回)
            out:
                -------[ next(d) ]-------
                minimize start

                -------[ print("result: ", d.send(1)) ]-------
                first current:  1
                while start
                result:  1

                -------[ print("result: ", d.send(-1)) ]-------
                value | current:  -1 | 1
                current:  -1
                while start
                result:  -1

                -------[ print("result: ", d.send(-1)) ]-------
                value | current:  -2 | -1
                current:  -2
                while start
                result:  -2
        """
    d = minimize()

    next(d)
    print("result: ", d.send(1))
    print("result: ", d.send(-1))
    print("result: ", d.send(-2))


if __name__ == '__main__':
    demo()
